協定
UIPickerViewDelegate,UIPickerViewDataSource,UITableView
協定僅宣告方法、屬性,不會直接定義內容,而是使其他服從此協定的class或struct來實作某些方法,或擁有某些屬性。
定義協定
//服從此協定的類別一定要實作giveMeSoyMilk方法
protocol SoyMilkGetable{
func giveMeSoyMilk()
}
使類別(Brunch)服從協定(SoyMilkGetable)
//Point:服從協定需時作協定中的方法
class Brunch:SoyMilkGetable{
func giveMeSoyMilk() {
print("SoyMilk")
}
}
試用看看
let aBrunch = Brunch()
aBrunch.giveMeSoyMilk() //Print:SoyMilk
以PickerView為例
protocol PickerViewDataSource{
func howManyComponent()
func howManyRow()
}
protocol PickerViewDelegate{
func titleToShow()
func didSelect()
}
//Point:一個類別可以服從多個協定,但是只能作為某一個類別的子類別
class ViewController:PickerViewDataSource,PickerViewDelegate{
func howManyComponent() {
print("2")
}
func howManyRow() {
print("10")
}
func titleToShow() {
print("hello")
}
func didSelect() {
print("select")
}
}
class PickerView{
var dataSource:PickerViewDataSource?
var delegate:PickerViewDelegate?
func howManyComponentIHave(){
dataSource?.howManyComponent()
}
func howManyRowIHave(){
dataSource?.howManyRow()
}
func whatToShow(){
delegate?.titleToShow()
}
func afterSelect(){
delegate?.didSelect()
}
}
let aPickerView = PickerView()
let aViewController = ViewController()
aPickerView.dataSource = aViewController
aPickerView.delegate = aViewController
aPickerView.howManyComponentIHave()
aPickerView.howManyRowIHave()